package com.keysen.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/upload")
@Api(value = "上传接口", tags = {"上传接口"})
public class UploadController {
    public static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Value("${upload.rootPath}")
    private String rootPath;

    @ApiOperation("上传文件")
    @RequestMapping(value = "/doUploadFile", method = RequestMethod.POST)
    public String doUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        try {
            String oldName = multipartFile.getOriginalFilename();
            String ext = oldName.substring(oldName.lastIndexOf("."));
            File parentFile = new File(rootPath);
            if(!parentFile.exists()){
                parentFile.mkdirs();
            }
            multipartFile.transferTo(new File(rootPath + File.separator + System.currentTimeMillis() + ext));
        } catch (IOException e) {
            logger.error("文件上传失败:" + e.getMessage(), e);
            return "文件上传失败";
        }
        return "ok";
    }
}
